package com.xinhe.web.weixin.service;

import com.xinhe.web.entity.WeixinConfig;
import com.xinhe.web.weixin.WXPayUtil;
import com.xinhe.web.weixin.WeixinAppPayParamView;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class WeixinAppTradeService {
    public WeixinAppPayParamView success(Map<String, String> response, WeixinConfig weixinConfig) {
        WeixinAppPayParamView payParam = new WeixinAppPayParamView();
        String nonceStr = response.get("nonce_str");
        String prepayId = response.get("prepay_id");
        String appId = response.get("appid");
        String paypackage = "Sign=WXPay";
        String timeStamp = (new Date()).getTime() + "";
        Map<String, String> signMap = new HashMap<>();
        signMap.put("appid", appId);
        signMap.put("partnerid", weixinConfig.getMchId());
        signMap.put("prepayid", prepayId);
        signMap.put("package", paypackage);
        signMap.put("noncestr", nonceStr);
        signMap.put("timestamp", timeStamp);
        try {
            String paySign = WXPayUtil.generateSignature(signMap, weixinConfig.getPayKey());
            payParam.setPaySign(paySign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        payParam.setAppId(appId);
        payParam.setMchId(weixinConfig.getMchId());
        payParam.setPrepayId(prepayId);
        payParam.setPaypackage(paypackage);
        payParam.setNonceStr(nonceStr);
        payParam.setTimeStamp(timeStamp);
        return payParam;
    }

    public WeixinAppPayParamView failure(String error) {
        WeixinAppPayParamView temp = new WeixinAppPayParamView();
        temp.setErroMsg(error);
        return temp;
    }
}
